/* Ken Moore 2003 - polymorphism */ #include #include using namespace std; class shape{ protected: double area; public: shape():area(0){} shape(double a):area(a){} // pure virtual version // precludes instantiating shape // virtual void computeArea() = 0; // not pure virtual, shape can be instantiated virtual void computeArea(){}; // without virtual in prototype: // no polymorphism virtual void show(string s)const{ cout << s << endl; cout << "in shape " << endl; cout << "area = " << area << endl; } }; class rect:public shape{ int x1, y1, x2, y2; public: rect():shape(-1){} rect(int a, int b, int c, int d):x1(a),y1(b),x2(c),y2(d){ area = (x2 - x1)*(y2 - y1); } void computeArea(){area = (x2 - x1)*(y2 - y1);}; void show(string s)const{ cout << s << endl; cout << "in rect " << endl; cout << "area = " << area << endl; cout << " x1 y1 " << x1 << " " << y1 << endl; cout << " x2 y2 " << x2 << " " << y2 << endl; } }; class circle:public shape{ int x, y; double radius; public: circle():shape(-1){} circle(int a, int b, double r):x(a),y(b),radius(r){ area = 3.14159*radius*radius; } void computeArea(){area = 3.14159*radius*radius;}; void show(string s)const{ cout << s << endl; cout << "in circle " << endl; cout << "area = " << area << endl; cout << " x y " << x << " " << y << endl; cout << " radius " << radius << endl; } }; void main(){ // try "shape s();" instead of "shape s;" // and see what happens - // compiler thinks it is a function prototype! shape s; s.show("show default shape variable "); rect r(0,0,2,4); r.show("show 0,0,2,4 rectangle"); circle c(10,10,1.0); c.show("show circle"); // show "slicing" problem s = r; s.show("variables polymorphic? y if rect n if shape!"); // not allowed //int *ip = new int(3); //double *dp = new double(2.71); //dp = ip; // perfectly ok? shape *sp, *sp2 = new shape(); rect *rp = new rect(0,0,2,4); circle *cp = new circle(10,10,1.0); sp = rp; // show how different elements can be // late bound via polymorphism sp->show("show rect via shape pointer"); shape *sps[3]; sps[0] = sp2; sps[1] = rp; sps[2] = cp; for(int i = 0; i < 3; i++) sps[i]->show("testing polymorph"); }